package com.byq.mcpanus.controller;

import com.byq.mcpanus.model.McpServer;
import com.byq.mcpanus.repository.McpServerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/server")
public class ServerController {
    @Autowired
    private McpServerRepository mcpServerRepository;

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list")
    public ResponseEntity<List<McpServer>> list() {
        return ResponseEntity.ok(mcpServerRepository.findAll());
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/{id}")
    public ResponseEntity<McpServer> get(@PathVariable Long id) {
        Optional<McpServer> server = mcpServerRepository.findById(id);
        return server.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public ResponseEntity<McpServer> create(@RequestBody McpServer server) {
        return ResponseEntity.ok(mcpServerRepository.save(server));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/update")
    public ResponseEntity<McpServer> update(@RequestBody McpServer server) {
        if (!mcpServerRepository.existsById(server.getId())) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(mcpServerRepository.save(server));
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/delete")
    public ResponseEntity<Void> delete(@RequestParam Long id) {
        if (!mcpServerRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        mcpServerRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
} 